package com.shop.shoporder.common;

//import com.sun.image.codec.jpeg.JPEGCodec;
//import com.sun.image.codec.jpeg.JPEGEncodeParam;
//import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;


public class AddWaterMark implements Serializable {


    /**
     * 图片添加水印
     *
     */
    public static String waterPress(String srcImgPath, String outImgPath, Color markContentColor, int fontSize, String waterMarkContent) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);


            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
//            Font font = new Font("Microsoft YaHei", Font.PLAIN, 16);
//            Font font = new Font("微软雅黑", Font.BOLD, 14);
            Font font = new Font("方正楷体简体", Font.PLAIN, 14);
            g.setColor(markContentColor);//根据图片的背景设置水印颜色
            g.setFont(font);

            int fontlen = getWatermarkLength(waterMarkContent, g);
//            int line = fontlen / srcImgWidth;//文字长度相对于图片宽度应该有多少行
//            int y = srcImgHeight - (line + 1)*fontSize;
            int y =490;


            System.out.println("水印文字总长度:" + fontlen + ",图片宽度:" + srcImgWidth + ",字符个数:" + waterMarkContent.length());

            //文字叠加,自动换行叠加
            int tempX = 5;
            int tempY = y;
            int tempCharLen = 0;//单字符长度
            int tempLineLen = 0;//单行字符总长度临时计算
            int lineCharCount = 10;//每行多少个字
            int s = 0;//每行的长度

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i <waterMarkContent.length(); i++) {

                char tempChar = waterMarkContent.charAt(i);
                if(' '== tempChar){
                    continue;
                }
                tempCharLen = getCharLen(tempChar, g);

                tempLineLen += tempCharLen;

                s = lineCharCount * tempCharLen;

                if (tempLineLen >s) {
                    //长度已经满一行,进行文字叠加
                    g.drawString(sb.toString(), tempX, tempY);

                    sb.delete(0, sb.length());//清空内容,重新追加

                    tempY += fontSize+5;

                    tempLineLen = 0;
                }

                sb.append(tempChar);//追加字符
            }

            g.drawString(sb.toString(), tempX, tempY);//最后叠加余下的文字
            g.dispose();

            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            ImageIO.write(bufImg, "png", outImgStream);
            System.out.println("-----水印添加完成：---->"+outImgPath);
            outImgStream.flush();
            outImgStream.close();
            return outImgPath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static int getCharLen(char c, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charWidth(c);
    }


    /**
     * 获取水印文字总长度
     *
     * @paramwaterMarkContent水印的文字
     * @paramg
     * @return水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }



    public static void createMark(String souchFilePath, String targetFilePath,
                                  String markContent, Color markContentColor, float qualNum,
                                  String fontType, int fontSize, int w, int h, Color color,String type,int drawSign) {
        markContentColor = color;
        ImageIcon imageIcon = new ImageIcon(souchFilePath);
        Image image = imageIcon.getImage();
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bImage.createGraphics();
        g.setColor(markContentColor);
        g.setBackground(Color.white);
        g.drawImage(image, 0, 0, null);


        int tempCharLen = 0;//单字符长度
        int tempLineLen = 0;//单行字符总长度临时计算
        int lineCharCount = 12;//每行多少个字

        int s = 0;//每行的长度
        //处理换行
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i <markContent.length(); i++) {
           markContent= markContent.replaceAll("\\s", "");
            char tempChar = markContent.charAt(i);
            String tempStr=tempChar+"";
            tempStr=String.format("%-1s",tempStr);
                tempLineLen+=tempStr.length();
                s=lineCharCount;

            if (tempLineLen >s) {
                AttributedString ats = new AttributedString(sb.toString());
                Font font=null;
                if("1".equalsIgnoreCase(type)){
                   font= new Font(fontType, Font.BOLD, fontSize);
                }else{
                    font = new Font(fontType, Font.PLAIN, fontSize);
                }

                g.setFont(font);

                g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                ats.addAttribute(TextAttribute.FONT, font, 0, sb.length());

                AttributedCharacterIterator iter = ats.getIterator();

                g.drawString(iter, width - w, height - h);

                h=h-fontSize-5;

                sb.delete(0, sb.length());

                tempLineLen = 0;
            }

            sb.append(tempStr);
        }


        AttributedString ats = new AttributedString(sb.toString());

        Font font=null;
        if("1".equalsIgnoreCase(type)||"4".equalsIgnoreCase(type)){
            font= new Font(fontType, Font.BOLD, fontSize);
        }else{
            font = new Font(fontType, Font.PLAIN, fontSize);
        }
        g.setFont(font);

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        ats.addAttribute(TextAttribute.FONT, font, 0, sb.length());

        AttributedCharacterIterator iter = ats.getIterator();

        g.drawString(iter, width - w, height - h);
        if(drawSign==1){
            g.drawLine(40,960,230,960);
        }


        g.dispose();
        try {
            FileOutputStream out = new FileOutputStream(targetFilePath);
            ImageIO.write(bImage,"png",out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
